package 多线程;

/*
    使用同步方法解决实现Runnable接口的线程安全问题
 */
public class ThreadTest07 {
    public static void main(String[] args) {
        Window3 w3 = new Window3();

        Thread t1 = new Thread(w3);
        t1.setName("线程一:");
        Thread t2 = new Thread(w3);
        t2.setName("线程二:");
        Thread t3 = new Thread(w3);
        t3.setName("线程三:");

        t1.start();
        t2.start();
        t3.start();
    }
}

//卖票
class Window3 implements Runnable{

    private int ticket = 100;
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.show();
        }
    }

    //如果操作共享数据的代码完整的声明在一个方法中,便可以将此方法声明为同步的,效果与同步代码块相同,此时同步监视器默认为this
    private synchronized void show(){
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + ":" + this.ticket--);
        }
    }
}
